package com.corn.juc.pool;

import java.sql.Time;
import java.util.concurrent.*;

/**
 * @author : Jim Wu
 * @version 1.0
 * @function :
 * @since : 2021/1/4 16:06
 */

public class ExecturosDemo {

    public static void main(String[] args) {
//        testFixThreadPool();
//        testSingleThreadPool();
//        testCachedThreadPool();
//        testScheduleThreadPool();
        testThreadPoolExecutor();
    }

    /**
     * threadPoolExecutor
     */
    private static void testThreadPoolExecutor() {
        ExecutorService executor = new ThreadPoolExecutor(2, 5, 1, TimeUnit.SECONDS, new LinkedBlockingQueue<>(3));
        for (int i = 0; i < 5; i++) {
            int finalI = i;
            executor.execute(() -> {
                try {
                    System.out.println(Thread.currentThread().getName() + "\t enter! task" + finalI);
                    TimeUnit.SECONDS.sleep(30);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        executor.execute(() -> {
            System.out.println(" over number work");
            System.out.println(Thread.currentThread().getName() + "\t enter!  task 6");
        });
    }

    /**
     * 带调度的线程池
     */
    private static void testScheduleThreadPool() {
        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(2);
        scheduledExecutorService.scheduleAtFixedRate(() -> System.out.println(Thread.currentThread().getName()), 1, 1, TimeUnit.SECONDS);
//        scheduledExecutorService.shutdown();
    }

    /**
     * 可伸缩的线程池
     */
    private static void testCachedThreadPool() {
        ExecutorService executorService = Executors.newCachedThreadPool();
        for (int i = 0; i < 5; i++) {
            executorService.submit(() -> System.out.println(Thread.currentThread().getName()));
        }
        // 一定记住要关闭
        executorService.shutdown();
    }

    /**
     * singleThreadPool
     */
    private static void testSingleThreadPool() {
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        for (int i = 0; i < 5; i++) {
            executorService.submit(() -> System.out.println(Thread.currentThread().getName()));
        }
        // 一定记住要关闭
        executorService.shutdown();
    }

    /**
     * 固定线程大小的ThreadPool
     */
    private static void testFixThreadPool() {
        ExecutorService executorService = Executors.newFixedThreadPool(5);
        for (int i = 0; i < 5; i++) {
            executorService.submit(() -> System.out.println(Thread.currentThread().getName()));
        }
        // 一定记住要关闭
        executorService.shutdown();
    }
}
